<template>
  <el-select
    v-bind="$attrs"
    v-model="value"
    :placeholder="props.placeholder"
    filterable
    @change="change"
  >
    <el-option
      v-for="item in currencyOptions"
      :key="item.id"
      :label="item.currency"
      :value="getValue(item)"
    />
  </el-select>
</template>
<script setup>
import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();
const currencyOptions = computed(() => {
  if (!commonStore.currencyOptions) {
    commonStore.getCurrencyList();
  }
  return commonStore.currencyOptions;
});

const props = defineProps({
  modelValue: [String, Number, Array],
  placeholder: {
    type: String,
    default: "请选择",
  },
  valueKey: {
    type: String,
    default: "id",
  },
});

const value = computed({
  get: () => {
    return props.modelValue;
  },
  set: (val) => {
    emit("update:modelValue", val);
  },
});

const emit = defineEmits(["update:modelValue", "change"]);
const change = (val) => {
  const item = currencyOptions.value.find((i) => i[props.valueKey] == val);
  emit("update:modelValue", val);
  emit("change", item?.currency);
  emit("changeItem", item);
};

const getValue = (item) => {
  return props.valueKey === "item" ? item : item[props.valueKey];
};

defineExpose({ change });
</script>
